package com.dsr.controller;

import com.dsr.consts.Result;
import com.dsr.consts.e.UserProperty;
import com.dsr.util.BasicUtil;
import com.dsr.util.RedisUtil;
import com.dsr.util.SendMailUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.concurrent.TimeUnit;

/**
 * @author dsr
 * @since 2020-10-15
 */
@RestController
@RequestMapping("/code")
public class CodeController {
    @Autowired
    private TemplateEngine templateEngine;

    @PostMapping("/get")
    public Result getCode(@RequestParam String title,@RequestParam String email) throws Exception {
        String code = BasicUtil.getCode();
        RedisUtil.setValue("userId"+BasicUtil.getToken(UserProperty.USER_ID),code,3, TimeUnit.MINUTES);
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                Context context = new Context();
                context.setVariable("code",code );
                String emailContent = templateEngine.process("emailTeplate", context);
                SendMailUtil.sendEmail(email,title,emailContent);
            }
        }).start();

        return  Result.success("获取成功");
    }

    @PostMapping("/check")
    public Result getCode(@RequestParam String code) throws Exception {
        String check = (String) RedisUtil.getValue("userId" + BasicUtil.getToken(UserProperty.USER_ID));
        if(StringUtils.isEmpty(check)){
            return Result.error("验证码过期");
        }
        if(check.equalsIgnoreCase(code)){
            return Result.success("成功");
        }else {
            return Result.error("验证码错误");

        }
    }

}
